
//
// copyright (c) 2014 vcg all right reserved.
//
//

window.onload = function(){
	olange.init();
};
var olange = {
	api : {
		readFileText : function( id , charset , events ){
			var fileAPISupported = false;
			var fileElement = null;
			fileElement = document.getElementById( id );
			if( fileElement == null ){
				return "";
			}
			// Check for the various File API support.
			if( window.File && window.FileReader && window.FileList && window.Blob ){
				// Great success! All the File APIs are supported.
				fileAPISupported = true;
			} else {
				fileAPISupported = false;
			}
			if( fileElement.files != null ){
				olange.properties.csvfilename = fileElement.files[0].name;
			}
			if( fileAPISupported == true ){
				var inputFile = fileElement.files[0];
				if( inputFile == null ){
					return "";
				}
				var reader = new FileReader();
				reader.onload = function( event ){
					if( events["onload"] != null ){
						events["onload"]( reader.result );
					}
				};
				reader.readAsText(inputFile,charset);
			}else if( window.navigator.userAgent.toLowerCase().indexOf("msie") != -1 ){
				var fs = new ActiveXObject( "Scripting.FileSystemObject" );
				//1:read , 2:write , 8:add
				var inf = fs.OpenTextFile( fileElement.value , 1 , true );
				var str = inf.ReadAll();
				inf.Close();
				if( events["onload"] != null ){
					events["onload"]( str );
				}
			}else{
				return "";
			}
		} , readFileImage : function( id , charset , events ){
			var files = document.getElementById( id ).files;
			if( files == null ){
				return "";
			}
			for( var i = 0; i < files.length; i++ ){
				var reader = new FileReader();
				reader.onerror = function (event) {
					alert("Error:load image file.");
				};
				if( files[i].type.match("image.*") ){
					reader.onload = ( function(f){
						return function(e) {
							if( events["onload"] != null ){
								events["onload"]( f , e , reader.result );
							}
						};
					} )(files[i]);
					reader.readAsDataURL(files[i]);
				}
			}
		} , writeFileText : function( filepath , filename , writedata , mimetype , charset ){
			var ua = navigator.userAgent.toLowerCase();

			var blobBuilder = null;
			var blob = null;
			var url = null;

			if( ua.indexOf("firefox") != -1
				|| ua.indexOf("chrome") != -1
			){
				if ("MSBlobBuilder" in window) {
					blobBuilder = new MSBlobBuilder();
					blobBuilder.append(writedata);
					blob = blobBuilder.getBlob(mimetype);
					window.navigator.msSaveOrOpenBlob(blob,filename);
					return ;
				} else if ("MozBlobBuilder" in window) {
					blobBuilder = new MozBlobBuilder();
					blobBuilder.append(writedata);
					blob = blobBuilder.getBlob();
				} else if ("WebKitBlobBuilder" in window) {
					blobBuilder = new WebKitBlobBuilder();
					blobBuilder.append(writedata);
					blob = blobBuilder.getBlob();
				} else if ("Blob" in window) {
					blob = new Blob(
						[writedata]
						, { type : mimetype }
					);
				}
				if( blob == null ){
					alert("faild.");
					return ;
				}
				if (window.URL) {
//					window.open( window.URL.createObjectURL( blob ) );
					url = window.URL.createObjectURL( blob );
				} else if (window.webkitURL) {
//					window.open( window.webkitURL.createObjectURL( blob ) );
					url = window.webkitURL.createObjectURL( blob );
				}
				var downloadElement = document.getElementById( "olange.html.saveCSVFile" );
				if( downloadElement != null ){
					downloadElement.href = url;
					downloadElement.download = filename;

				}
			} else if( ua.indexOf("msie") != -1 ){
				if ("MSBlobBuilder" in window) {
					blobBuilder = new MSBlobBuilder();
					blobBuilder.append(writedata);
					blob = blobBuilder.getBlob(mimetype);
					window.navigator.msSaveOrOpenBlob(blob,filename);
					return ;
				}
			}else{
				if ("MSBlobBuilder" in window) {
					blobBuilder = new MSBlobBuilder();
					blobBuilder.append(writedata);
					blob = blobBuilder.getBlob(mimetype);
					window.navigator.msSaveOrOpenBlob(blob,filename);
					return ;
				}else{
					alert("Sorry.\nIt is not support.");
				}
			}
		} , deleteCommentLine : function( text , headerString ){
			if( text == null
				|| headerString == null
				){
				return text;
			}
			var start = 0;
			var headerIndex = 0;
			var newLineIndex = 0;
			while( true ){
				headerIndex = text.indexOf( headerString , start );
				if( headerIndex == -1 ){
					break;
				}
				newLineIndex = text.indexOf( "\n" , headerIndex + 1 );
				text = text.substring( 0 , headerIndex ) + text.substring( newLineIndex + 1 , text.length );
				start = headerIndex;
			}
			return text;
		} , replace : function( text , oldString , newString ){
			if( text == null
				|| oldString == null
				|| oldString.length == 0
				|| newString == null
				|| newString.length == 0
				){
				return text;
			}
			var start = 0;
			var index = 0;

			while( true ){
				index = text.indexOf( oldString , start );
				if( index == -1 ){
					break;
				}
				text = text.substring( 0 , index )
					+ newString
					+ text.substring( index + oldString.length , text.length )
				;
				start = index + newString.length + 1;
			}
			return text;
		}
	} , init : function(){

		var olangeElement = document.getElementById( "olange" );
		if( olangeElement == null ){
			olangeElement = document.createElement( "div" );
			olangeElement.id = "olange";
			olangeElement.setAttribute( "ondragover" , "olange.method.onDragOver(event)" );
			olangeElement.setAttribute( "ondrop" , "olange.method.onDrop(event)" );
			olangeElement.style.backgroundColor = "#f8ffff";
			olangeElement.style.border = "solid 1px #808080";
			document.body.appendChild( olangeElement );
		}

		//html
		var olangeMenuElement = document.getElementById( "olange.html" );
		if( olangeMenuElement == null ){
			olangeMenuElement = document.createElement( "div" );
			olangeMenuElement.id = "olange.html";
			olangeMenuElement.style.border = "solid 1px #808080";
			olangeElement.appendChild( olangeMenuElement );
		}
		olange.view.renewMenu();

		//tipPallet
		var olangeTipPalletElement = document.getElementById( olange.model.tipPallet.name );
		if( olangeTipPalletElement == null ){
			olangeTipPalletElement = document.createElement( "div" );
			olangeTipPalletElement.id = olange.model.tipPallet.name;
			olangeTipPalletElement.style.display = "";
			olangeTipPalletElement.style.border = "solid 1px #808080";
			olangeElement.appendChild( olangeTipPalletElement );
		}
		olange.view.renewTipPallet();

		//status
		var olangeStatusElement = document.getElementById( "olange.status" );
		if( olangeStatusElement == null ){
			olangeStatusElement = document.createElement( "div" );
			olangeStatusElement.id = "olange.status";
			olangeStatusElement.style.border = "solid 1px #808080";
			olangeElement.appendChild( olangeStatusElement );
		}
		olange.view.renewStatus();


		//map
		var olangeMapElement = document.getElementById( olange.model.map.name );
		if( olangeMapElement == null ){
			olangeMapElement = document.createElement( "div" );
			olangeMapElement.id = olange.model.map.name;
			olangeMapElement.style.display = "";
			olangeMapElement.style.border = "solid 1px #808080";
			olangeElement.appendChild( olangeMapElement );
		}

		//copyright
		var olangeCopyrightElement = document.getElementById( "olange.copyright" );
		if( olangeCopyrightElement == null ){
			olangeCopyrightElement = document.createElement( "span" );
			olangeCopyrightElement.innerHTML = "<span>copyright (c) 2014 vcg all right reserved.<span>";
			olangeElement.appendChild( olangeCopyrightElement );
		}
	} , properties : {
		CRLF : "\r\n"
		, CR : "\r"
		, LF : "\n"
		, sharp : "#"
		, comma : ","
		, mapCellSize : "100%"
		, fileAPISupported : false
		, csvfilename : "test.csv"
	} , html : {
		readCSVFile : {
			htmltag : "readCSVFile<input id=\"olange.html.readCSVFile\" name=\"olange.html.readCSVFile\" value=\"readCSVFile\" type=\"file\" onchange=\"olange.html.readCSVFile.func()\" >"
			, id : "olange.html.readCSVFile"
			, name : "olange.html.readCSVFile"
			, type : "file"
			, value : "readCSVFile"
			, eventname : "onchange"
			, func : function(){
				olange.api.readFileText( "olange.html.readCSVFile" , "shift-jis" , olange.method.readCSVFile );
			}
		} ,readImageFile : {
			htmltag : "readImageFile<input id=\"olange.html.readImageFile\" name=\"olange.html.readImageFile\" value=\"readImageFile\" type=\"file\" multiple=\"\" accept=\"image/*\" onchange=\"olange.html.readImageFile.func()\" >"
			, id : "olange.html.readImageFile"
			, name : "olange.html.readImageFile"
			, type : "file"
			, value : ""
			, eventname : "onchange"
			, func : function(){
				olange.api.readFileImage( "olange.html.readImageFile" , "shift-jis" , olange.method.readImageFile );
			}
		} , saveCSVFile : {
//			htmltag : "saveCSVFile<input id=\"olange.html.saveCSVFile\" name=\"olange.html.saveCSVFile\" value=\"saveCSVFile\" type=\"button\" onclick=\"olange.html.saveCSVFile.func()\" >"
			htmltag : "<a href=\""+"\" id=\"olange.html.saveCSVFile\" download=\""+"\" onclick=\"olange.html.saveCSVFile.func()\" >get csv file</a>"
			, id : "olange.html.saveCSVFile"
			, name : "olange.html.saveCSVFile"
			, type : "button"
			, value : "saveCSVFile"
			, eventname : "onclick"
			,func : function(){
				var writedata = "";
				var tmpStr = "";
				for( var y = 0; y < olange.model.map.height; y++ ){
					tmpStr = "";
					for( var x = 0; x < olange.model.map.width; x++ ){
						tmpStr += olange.model.map.mapData[ y * olange.model.map.width + x ];
						tmpStr += olange.properties.comma;
					}
					writedata += tmpStr.substring(0,tmpStr.length-1);
					writedata += olange.properties.CRLF;
				}
				olange.api.writeFileText("c:\\tmp\\",olange.properties.csvfilename,writedata,"text/comma-separated-values","shift-jis");
			}
		} , renewMap : {
			htmltag : "<input id=\"olange.html.renewMap\" name=\"olange.html.renewMap\" value=\"renewMap\" type=\"button\" onclick=\"olange.html.renewMap.func()\" >"
			, id : "olange.html.renewMap"
			, name : "olange.html.renewMap"
			, type : "button"
			, value : "renewMap"
			, eventname : "onclick"
			, func : function(){
//				olange.view.renewMap();
				olange.api.readFileText( "olange.html.readCSVFile" , "shift-jis" , olange.method.readCSVFile );
			}
		} , visibleMap : {
			htmltag : "<input id=\"olange.html.visibleMap\" name=\"olange.html.visibleMap\" value=\"visibleMap\" type=\"button\" onclick=\"olange.html.visibleMap.func()\" >"
			, id : "olange.html.visibleMap"
			, name : "olange.html.visibleMap"
			, type : "button"
			, value : "visibleMap"
			, eventname : "onclick"
			, func : function(){
				olange.method.visibleMap();
			}
		} , visibleTipPallet : {
			htmltag : "<input id=\"olange.html.visibleTipPallet\" name=\"olange.html.visibleTipPallet\" value=\"visibleTipPallet\" type=\"button\" onclick=\"olange.html.visibleTipPallet.func()\" >"
			, id : "olange.html.visibleTipPallet"
			, name : "olange.html.visibleTipPallet"
			, type : "button"
			, value : "visibleTipPallet"
			, eventname : "onclick"
			,func : function(){
				olange.method.visibleTipPallet();
			}
		}
	} , status : {
		selectTipImage : "."
		, selectTipValue : ""
		, id : "olange.status.id"
		, resetTipImage : function(){
			this.selectTipImage = ".";
			this.selectTipValue = "";
			var statusElement = document.getElementById( this.id );
			if( statusElement != null ){
				statusElement.src = this.selectTipImage;
			}
		} , mouseDown : -1
		, mouseDownPositionX : -1
		, mouseDownPositionY : -1
	} , model : {
		map : {
			name : "Map"
			, width : 0
			, height : 0
			, mapData : []
			, init : function(){
				this.width = 0;
				this.height = 0;
				this.mapData = [];
			} , add : function( value ){
				if( this.mapData == null ){
					return;
				}
				this.mapData[ this.mapData.length ] = value;
			} , at : function( index ){
				if( this.mapData == null
						|| index < 0
						|| index >= this.mapData.length
						){
					return "";
				}
				return this.mapData[ index ];
			}
		} , tipPallet : {
			name : "TipPallet"
			, tips : []
			, add : function( id , filepath ){
				if( this.tips == null ){
					this.tips = [];
				}
				this.tipindex.add(id,this.tips.length);
				this.tips[this.tips.length] = this.createTip( id , filepath );
			} , get : function( id ){
				if( id == null
					|| this.tips == null
				){
					return "";
				}
				if( this.tips[id] == null ){
					return "";
				}
				return this.tips[id];
			} , at : function( index ){
				if( index == null
					|| index < 0
					|| this.tips == null
					|| index >= this.tips.length
				){
					return "";
				}
				if( this.tips[index] == null ){
					return "";
				}
				return this.tips[index];
			} , set : function( index , newId , newFilepath ){
				if( this.tips == null ){
					this.tips = [];
				}
				this.tips[index] = this.createTip( newId , newFilepath );
			} , length : function(){
				return this.tips.length;
			} , createTip : function( id , filepath ){
				var tmptip = {
					id : ""
					,filepath : ""
				};
				tmptip.id = id;
				tmptip.filepath = filepath;
				return tmptip;
			} , tipindex : {
				name : "tipindex"
				,tipindex : []
				,add : function( id , index ){
					if( this.tipindex == null ){
						this.tipindex = [];
					}
					this.tipindex[id] = index;
				} ,get : function( id ){
					if( id == null
						|| id == ""
						|| this.tipindex == null
					){
						return "";
					}
					if( this.tipindex[id] == null ){
						return "";
					}
					return this.tipindex[id];
				}
			}
		}
	} , method : {
		onDragOver : function( event ){
			event.preventDefault();
		} , onDrop : function( event ){
			var files = event.dataTransfer.files;

			for( var i=0; i<files.length; i++){
				if( ( !files[i].type.match("image.*") && !files[i].type.match("text.*") ) ){
					continue;
				}
				var reader = new FileReader();
				reader.onerror = function (event) {
					alert("Error:load drop file.");
				};
				if( files[i].type.match("image.*") ){
					reader.onload = ( function(f){
						return function(e) {
							olange.model.tipPallet.add( f.name , e.target.result );
							olange.view.renewTipPallet();
						};
					} )(files[i]);
					reader.readAsDataURL(files[i]);
				}
			}
			event.preventDefault();
		} , readCSVFile : {
			onload : function( csvdata ){

				if( csvdata == null
						){
					return ;
				}

				var count = 0;
				var w = 0;
				var h = 0;
				var diffcount = 0;
				var value;

				csvdata = olange.api.replace( csvdata , olange.properties.CRLF , olange.properties.LF );
				csvdata = olange.api.replace( csvdata , olange.properties.LF + olange.properties.LF , olange.properties.LF );
				csvdata = olange.api.deleteCommentLine( csvdata , olange.properties.sharp );
				var lines = csvdata.split( olange.properties.LF );

				olange.model.map.init();

				for( var i = 0; i < lines.length; i++ ){
					if( lines[i].length == 0 ){
						continue;
					}
					count = 0;
					value = lines[i].split( olange.properties.comma );
					for( var j = 0; j < value.length; j++ ){
						olange.model.map.add( value[j] );
						count++;
					}
					if( w != count ){
						diffcount++;
					}
					w = count;
					h++;
				}

				olange.model.map.width = w;
				olange.model.map.height = h;

				olange.view.renewMap();
			}
		} , readImageFile : {
			onload : function( file , event , result ){
				olange.model.tipPallet.add( file.name , event.target.result );
				olange.view.renewTipPallet();
			}
		} , visibleMap : function(){
			var olangeMapElement = document.getElementById( olange.model.map.name );
			if( olangeMapElement != null ){
				if( olangeMapElement.style.display == "" ){
					olangeMapElement.style.display = "none";
				}else{
					olangeMapElement.style.display = "";
				}
			}else{
				return;
			}
			var olangeCommandElement = document.getElementById( olange.html["visibleMap"].name );
			if( olangeCommandElement != null ){
				if( olangeMapElement.style.display == "" ){
					olangeCommandElement.value = "hideMap";
				}else{
					olangeCommandElement.value = "showMap";
				}
			}
		} , visibleTipPallet : function(){
			var olangeTipPalletElement = document.getElementById( olange.model.tipPallet.name );
			if( olangeTipPalletElement != null ){
				if( olangeTipPalletElement.style.display == "" ){
					olangeTipPalletElement.style.display = "none";
				}else{
					olangeTipPalletElement.style.display = "";
				}
			}else{
				return;
			}
			var olangeCommandElement = document.getElementById( olange.html["visibleTipPallet"].name );
			if( olangeCommandElement != null ){
				if( olangeTipPalletElement.style.display == "" ){
					olangeCommandElement.value = "hideTipPallet";
				}else{
					olangeCommandElement.value = "showTipPallet";
				}
			}

		} , selectMapCell : function( kind , index ){
			if( kind == "mousedown" ){
				olange.status.mouseDown = 1;
				olange.status.mouseDownPositionX = index % olange.model.map.width;
				olange.status.mouseDownPositionY = ~~( index / olange.model.map.width );
			}else if( kind == "mouseup" ){
				if( olange.status.mouseDown == 1 ){
					var startX = olange.status.mouseDownPositionX;
					var startY = olange.status.mouseDownPositionY;
					var endX = index % olange.model.map.width;
					var endY = ~~( index / olange.model.map.width );
					if( startX > endX ){
						endX = startX;
						startX = index % olange.model.map.width;
					}
					if( startY > endY ){
						endY = startY;
						startY = ~~( index / olange.model.map.width );
					}
					for( var h = startY; h <= endY ; h++ ){
						for( var w = startX; w <= endX; w++ ){
							olange.view.renewMapCell( h * olange.model.map.width + w );
						}
					}

					olange.status.mouseDown = -1;
					olange.status.mouseDownPositionX = -1;
					olange.status.mouseDownPositionY = -1;
				}
			}
		} , selectTip : function( index ){
			var tip = olange.model.tipPallet.tips[ index ];
			if( tip == null ){
				return;
			}
			olange.status.selectTipImage = tip.filepath;
			olange.status.selectTipValue = tip.id;
			olange.view.renewStatus();
		}
	} , view : {
		renewMenu : function(){
			//html
			var olangeMenuElement = document.getElementById( "olange.html" );
			if( olangeMenuElement == null ){
				return ;
			}
			var htmlStr = "";

			//html
			htmlStr += "<table cellpadding=\"0\" cellspacing=\"0\" >"+olange.properties.LF+"<tr>"+olange.properties.LF;
			for( prop in olange.html ){
				htmlStr += "<td>"+olange.html[prop].htmltag+"</td>"+olange.properties.LF;
			}
			htmlStr += "</tr>"+olange.properties.LF+"</table>"+olange.properties.LF;

			olangeMenuElement.innerHTML = htmlStr;
		} , renewStatus : function(){
			var htmlStr = "";

			var olangeStatusElement = document.getElementById( "olange.status" );
			if( olangeStatusElement == null ){
				return;
			}

			htmlStr += "<table cellpadding=\"0\" cellspacing=\"0\" >"+olange.properties.LF+"<tr>"+olange.properties.LF;
			htmlStr += "<td>"+"<input value=\"Choice reset.\" type=\"button\" onclick=\"olange.status.resetTipImage()\" >Current choice:"+"</td>"+olange.properties.LF;
			htmlStr += "<td>"+"<img id=\""+olange.status.id+"\" src=\""+olange.status.selectTipImage+"\">"+"</td>"+olange.properties.LF;
			htmlStr += "<td>"+olange.status.selectTipValue+"</td>"+olange.properties.LF;

			htmlStr += "</tr>"+olange.properties.LF+"</table>"+olange.properties.LF;

			olangeStatusElement.innerHTML = htmlStr;
		} , renewMapCell : function( index ){
			var olangeMapCellElement = document.getElementById( "mapCell_" + index );
			if( olangeMapCellElement == null
					|| olange.status.selectTipValue == null
					|| olange.status.selectTipImage == null
			){
				return ;
			}
			olange.model.map.mapData[index] = olange.status.selectTipValue;
			olangeMapCellElement.src = olange.status.selectTipImage;
		} , renewMap : function(){
			var htmlStr = "";

			var olangeMapElement = document.getElementById( olange.model.map.name );
			if( olangeMapElement == null ){
				return ;
			}else if( olange.model.tipPallet.tips == null
					|| olange.model.tipPallet.tips.length == 0
					|| olange.model.map.mapData == null
					|| olange.model.map.mapData.length == 0
					){
				return ;
			}

			var tmpImgTip = null;
			htmlStr += "<table cellpadding=\"0\" cellspacing=\"0\" >"+olange.properties.LF;
			for( var h = 0 ;h < olange.model.map.height; h++ ){
				htmlStr += "<tr>"+olange.properties.LF;
				for( var w = 0 ;w < olange.model.map.width; w++ ){
					tmpImgTip = olange.model.tipPallet.at(
						olange.model.tipPallet.tipindex.get(
							olange.model.map.at( ( h * olange.model.map.width + w ) )
						)
					);
					if( tmpImgTip != null
							&& tmpImgTip != ""
							&& tmpImgTip.filepath != null
							&& tmpImgTip.filepath != ""
					){
						htmlStr += "<td>"+"<img draggable=\"false\" id=\"mapCell_"+(h*olange.model.map.width+w)+"\" src=\""+tmpImgTip.filepath +"\" onmousedown=\"olange.method.selectMapCell('mousedown','"+(h*olange.model.map.width+w)+"')\" onmouseup=\"olange.method.selectMapCell('mouseup','"+(h*olange.model.map.width+w)+"')\" >"+"</td>";
					}else{
						htmlStr += "<td>"+"<img draggable=\"false\" id=\"mapCell_"+(h*olange.model.map.width+w)+"\" src=\".\" onmousedown=\"olange.method.selectMapCell('mousedown','"+(h*olange.model.map.width+w)+"')\" onmouseup=\"olange.method.selectMapCell('mouseup','"+(h*olange.model.map.width+w)+"')\" >"+"</td>";
					}
				}
				htmlStr += "</tr>"+olange.properties.LF;
			}
			htmlStr += "</table>"+olange.properties.LF;

			olangeMapElement.innerHTML = htmlStr;
		} , renewTipPallet : function(){
			var html = "";
			var colsize = 8;

			var olangeTipPalletElement = document.getElementById( olange.model.tipPallet.name );
			if( olangeTipPalletElement == null ){
				return;
			}

			html += "<table cellpadding=\"0\" cellspacing=\"0\" >"+olange.properties.LF;

			for( var row = 0; row < ~~( olange.model.tipPallet.tips.length / colsize ) ; row++ ){
				html += "<tr>"+olange.properties.LF;
				for( var col = 0 ; col < colsize ; col++ ){
					html += "<td>";
					html += "<img src=\""+olange.model.tipPallet.tips[ row * colsize + col ].filepath+"\" onclick=\"olange.method.selectTip('"+( row * colsize + col )+"')\" >";
					html += "</td>";
				}
				html += "</tr>"+olange.properties.LF;
			}
			html += "<tr>"+olange.properties.LF;
			for( var col = 0 ; col < olange.model.tipPallet.tips.length % colsize ; col++ ){
				html += "<td>";
				html += "<img src=\""+olange.model.tipPallet.tips[ ~~( olange.model.tipPallet.tips.length / colsize ) * colsize + col ].filepath+"\" onclick=\"olange.method.selectTip('"+(~~( olange.model.tipPallet.tips.length / colsize ) * colsize + col )+"')\" >";
				html += "</td>";
			}
			html += "</tr>"+olange.properties.LF+"</table>"+olange.properties.LF;

			olangeTipPalletElement.innerHTML = html;

		}
	}
};


